import Toast from '@vant/weapp/toast/toast';
const { authorization } = require('../../../../utils/location')

// 获取当前位置
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        orderAll: [],  //查询全部数据
        activeNames: ['0'], //点击折叠
        driver_orders: [],
        wms_address: {},
        show_logo: [],
        // show_photo:[],
        //Map
        latitude: 0,
        longitude: 0,
        scale: 12.1, //3-20
        is_edit: false,
        update_location_text: '调整定位',
        is_update_location: false,

        update_type: -1,
        markers: [],

        polyline: [],
        center_location: undefined,
        tempFilePaths: [],
        //备注以及上传照片相关
        show_popup: false,
        max_size: 1048576 * 3, //单图片大小

        //图片预览
        indicatordots: true,
        //是否显示面板指示点
        autoplay: false, //是否自动切换
        interval: 5000, //自动切换时间间隔
        duration: 500, //滑动动画时长
        color: '#ffffff', //当前选中的指示点颜色
        height: '',
        delivery_address_classic: '',
        view_delivery_man_id: 0,
        view_driver_name: '',
        view_delivery_district_id: 0,
        classification: '' //经营类别
        //swiper高度
    },

    switch_show_center: async function (e) {
        if (this.data.is_edit) {
            this.setData({
                'is_edit': false,
                'scale': 12,
                'update_location_text': '调整定位'
            })


            this.map = wx.createMapContext('locationM', this)

            if (this.data.longitude === undefined) {
                let res = await authorization()
            }

            let res = await authorization()
            this.map.moveToLocation({
                longitude: Number(this.data.longitude),
                latitude: Number(this.data.latitude),
                success: function () {
                    console.log("成功将地图中心移到定位点")
                }
            })
            Toast('结束定位调整。')
        } else {
            this.setData({
                'scale': 18,
                'is_edit': true,
                'update_location_text': '结束调整'
            })

            let order = this.data.order
            this.map = wx.createMapContext('locationM', this)
            this.map.moveToLocation({
                latitude: Number(order.latitude),
                longitude: Number(order.longitude),
                success: function () {
                    console.log("成功将地图中心移到定位点")
                }
            })

            Toast('拖动要定位的位置到中心知识点，然后更新对应的定位即可。')

        }
    },

    bindregionchange: function (e) {
        if (!this.data.is_edit) {
            return;
        }
        if (!(e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag'))) {
            return
        }
        let center_location = e.detail.centerLocation;
        this.setData({
            'center_location': center_location
        })
    },

    bindmarkertap: function (e) {
        /*
        locationUtils.getLocation().then(res => {
            console.log('当前所在位置的经纬度为：')
            console.log(res.latitude,res.longitude)
        })

        */
    },

    ballPopup(e) {
        //let id = e.currentTarget.dataset.id //获取传递的id参数
        //let ordername = e.currentTarget.dataset.ordername
        this.setData({
            show_popup: true,
        }) //打开弹窗
    },
    onPopupClose() {
        this.setData({
            show_popup: false,
        })
    },

    /* 上传文件查看图片大小 */
    imgSize(event) {
        let imgMax = this.data.address_image_max_size; //获取默认上传文件大小
        const {
            file
        } = event.detail; //获取上传文件数组
        for (let i = 0; i < file.length; i++) {
            if (file[i].size > imgMax) {
                Toast('大小超过2MB~')
            }
        }
    },
    /* 上传文件后事件，处理照片放入OSS回显 */
    afterRead(event) {
        let that = this
        const { file } = event.detail;
        for (let i = 0; i < file.length; i++) {
            wx.uploadFile({
                url: 'https://helper.fuduoduoshop.com/api/v1/file/images',
                filePath: file[i]['url'], //传递文件
                header: {
                    'Content-Type': 'application/json',
                    "x-api-key": this.data.access_token,
                },
                name: 'file', //获取照片信息的名称
                formData: {
                    drive: 'qiniu',
                    thumb: JSON.stringify([{
                        width: 100,
                        height: 100
                    }])
                },

                success(res) {
                    let response = JSON.parse(res.data) //传过来的是json 需要转换成对象
                    let code = response.code
                    if (code === 200) {
                        let wms_address = that.data.wms_address
                        console.log(wms_address)
                        wms_address.logo.push({
                            url: response.data.url,
                            name: response.data.name,
                            isImage: true,
                        })

                        that.setData({
                            wms_address
                        })
                    }
                }
            })
        }
    },
    /**
     * 删除上传的照片
     */

    previewMultipleImages(e) {
        console.log(e)
        const current = e.currentTarget.dataset.url;
        console.log(current)
        console.log(this.data.show_logo)
        const urls = this.data.show_logo.map(item => item.url);
        console.log(urls)
        wx.previewImage({
            current: current, // 当前显示图片的链接
            urls: urls // 需要预览的图片链接列表
        })
    },
    imgDeleteLogo(event) {
        this.imgDelete(event, 1)
    },
    imgDeletePhoto(event) {
        this.imgDelete(event, 2)
    },
    imgDelete(event, image_type) {
        let that = this;
        let urlPath = event.detail.file.url
        wx.request({
            url: app.globalData.API + '/delivery/index/delete-qiniu-image',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": that.data.access_token,
            },
            data: {
                path: urlPath
            },
            method: "POST",
            success: res => {
                if (res.data.code === 200) {
                    const success = res.data.data;
                    if (success) {
                        let wms_address = that.data.wms_address
                        if (image_type === 1) {
                            // 删除 wms_address.logo 中与 urlPath 匹配的项
                            wms_address.logo = wms_address.logo.filter(item => item.url !== urlPath);
                            wms_address.logo = wms_address.logo.filter(item => item.url.url !== urlPath);
                        } else if (image_type === 2) {
                            // 删除 wms_address.logo 中与 urlPath 匹配的项
                            wms_address.photo = wms_address.photo.filter(item => item.url !== urlPath);
                            wms_address.photo = wms_address.photo.filter(item => item.url.url !== urlPath);
                        }
                        that.setData({
                            wms_address
                        })
                    }
                }
            }
        });
    },


    save_address_location: function () {
        this.save_location(0)
        Toast('已更新店铺定位')
    },
    save_tricycle_stop_location: function () {
        this.save_location(1)
        Toast('已更新三路车驻车点定位')
    },
    save_vehicle_stop_location: function () {
        this.save_location(2)
        Toast('已更新货车驻车点定位')
    },

    onInputChange(e) {
        console.log(e)
        let value = e.detail; // 获取输入框的值
        const keyName = e.currentTarget.dataset.keyname;
        console.log(keyName, value)

        let wms_address = this.data.wms_address
        wms_address[keyName] = value;

        // 更新 wms_address 对象中的对应字段
        this.setData({
            wms_address
        });
    },

    submit_wms_address_remark(e) {
        let that = this
        let wms_address = that.data.wms_address
        console.log(wms_address)
        wx.request({
            url: app.globalData.API + '/delivery/index/remark-address',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                wms_address
            },
            success(res) {
                if (res.data.code === 200) {
                    that.setData({
                        wms_address,
                    })
                    Toast('提交成功~')
                    that.onPopupClose()
                } else {
                    Toast('提交失败~')
                }
            }
        })
    },


    save_location: function (location_type) {
        let that = this
        let order = that.data.order

        let customer_id = order['customer_id']
        let address_id = order['address_id']
        let center_location = that.data.center_location

        let location = center_location.longitude + ',' + center_location.latitude

        wx.request({
            url: app.globalData.API + '/delivery/index/update-address-location',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                customer_id,
                address_id,
                location,
                location_type
            },
            success(res) {
                if (res.data.code === 200) {
                    Toast('更新成功~')
                } else {
                    Toast('更新失败~')
                }
            }
        })
    },

    goheight: function (e) {
        var width = wx.getSystemInfoSync().windowWidth
        //获取可使用窗口宽度
        var imgheight = e.detail.height
        //获取图片实际高度
        var imgwidth = e.detail.width
        //获取图片实际宽度
        var height = width * imgheight / imgwidth + "px"
        //计算等比swiper高度
        this.setData({
            height: height
        })
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        let view_delivery_man_id = wx.getStorageSync('view_delivery_man_id') || 0
        let view_driver_name = ''
        let view_delivery_district_id = 0
        if (view_delivery_man_id > 0) {
            view_driver_name = wx.getStorageSync('view_driver_name')
            view_delivery_district_id = wx.getStorageSync('view_delivery_district_id')
        }

        let access_token = wx.getStorageSync('access_token')
        let delivery_man = wx.getStorageSync('delivery_man')
        let delivery_district = wx.getStorageSync('delivery_district')
        let delivery_district_list = wx.getStorageSync('delivery_district_list')
        let delivery_list = wx.getStorageSync('delivery_list')
        this.setData({
            'access_token': access_token,
            'delivery_man': delivery_man,
            'delivery_district': delivery_district,
            'delivery_district_list': delivery_district_list,
            'delivery_list': delivery_list,
            'current_delivery_district_id': 0,
            'level': delivery_man.level,
        })

        this.setData({
            view_delivery_man_id,
            view_driver_name,
            view_delivery_district_id
        })

        let that = this
        // wx.getLocation({
        //     type: "gcj02",
        //     success(res) {

        //         let xian_latitude = 34.26986287676798
        //         let xian_longitude = 108.9471324706426

        //         let map_latitude = xian_latitude
        //         let map_longitude = xian_longitude
        //         if (that.getDistance(xian_latitude, xian_longitude, res.latitude, res.longitude) < 300) {
        //             map_latitude = res.latitude
        //             map_longitude = res.longitude
        //         }

        //         that.setData({
        //             latitude: res.latitude,
        //             longitude: res.longitude,


        //         })
        //     }
        // })
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('orderInfo', function (res) {
            //
            let orderInfo = JSON.parse(res)
            let order = orderInfo['order']
            let mergeOrders = orderInfo['mergeOrders'] ?? []
            let orders = [order, ...mergeOrders];
            let markers = []
            let address_marker = {
                iconPath: "../../img/icon-hc.png",
                id: 900000000 + parseInt(order.order_id),
                order_id: order.order_id,
                latitude: Number(order.latitude),
                longitude: Number(order.longitude),
                width: 23,
                height: 23,
                callout: {
                    content: order.contact,
                    fontSize: 14,
                    padding: true,
                    color: '#ffffff',
                    display: 'ALWAYS',
                    textAlign: 'center',
                    borderRadius: 10,
                    bgColor: '#0077ffbe'
                },
            }
            markers.push(address_marker)

            // let tricycle_stop_marker = {}
            // let vehicle_stop_marker = {}
            let wms_address = order['wms_address'] || []
            // if (wms_address) {
            //     address_marker.latitude = Number(wms_address.latitude)
            //     address_marker.longitude = Number(wms_address.longitude)

            //     if (wms_address['tricycle_stop_location'].indexOf(',') > 0) {
            //         let location = wms_address['tricycle_stop_location'].split(',')
            //         tricycle_stop_marker = {
            //             iconPath: "../../img/tricycle.png",
            //             id: 1,
            //             latitude: Number(location[1]),
            //             longitude: Number(location[0]),
            //             width: 12,
            //             height: 6,
            //             callout: {
            //                 content: '三轮停车点',
            //                 fontSize: 14,
            //                 padding: true,
            //                 color: '#ffffff',
            //                 display: 'ALWAYS',
            //                 textAlign: 'center',
            //                 borderRadius: 10,
            //                 bgColor: '#0077ffbe'
            //             },
            //         }
            //     }

            //     // if (wms_address['vehicle_stop_location'].indexOf(',') > 0) {
            //     //     let location = wms_address['vehicle_stop_location'].split(',')
            //     //     vehicle_stop_marker = {
            //     //         iconPath: "../../img/truck.png",
            //     //         id: 2,
            //     //         latitude: Number(location[1]),
            //     //         longitude: Number(location[0]),
            //     //         width: 12,
            //     //         height: 6,
            //     //         callout: {
            //     //             content: '货车停车点',
            //     //             fontSize: 14,
            //     //             padding: true,
            //     //             color: '#ffffff',
            //     //             display: 'ALWAYS',
            //     //             textAlign: 'center',
            //     //             borderRadius: 10,
            //     //             bgColor: '#0077ffbe'
            //     //         },
            //     //     }
            //     // }
            // }
            markers.push(address_marker)
            let polyline = []
            // if (Object.keys(tricycle_stop_marker).length > 0) {
            //     markers.push(tricycle_stop_marker)
            //     polyline.push({
            //         points: [
            //             {longitude: tricycle_stop_marker.longitude, latitude: tricycle_stop_marker.latitude},
            //             {longitude: address_marker.longitude, latitude: address_marker.latitude},
            //         ],
            //         color: "#FF0000DD",
            //         width: 2,
            //         dottedLine: true,
            //     })
            // }
            // if (Object.keys(vehicle_stop_marker).length > 0) {
            //     markers.push(vehicle_stop_marker)
            //     polyline.push({
            //         points: [
            //             {longitude: vehicle_stop_marker.longitude, latitude: vehicle_stop_marker.latitude},
            //             {longitude: address_marker.longitude, latitude: address_marker.latitude},
            //         ],
            //         color: "#FF0000DD",
            //         width: 2,
            //         dottedLine: true,
            //     })
            // }

            wms_address.logo = that.parseJsonOrEmptyArray(wms_address.logo)
            wms_address.photo = that.parseJsonOrEmptyArray(wms_address.photo)

            let show_logo = wms_address.logo
            let show_photo = wms_address.photo
            that.setData({
                order: order,
                orders: orders,
                wms_address: wms_address,
                markers: markers,
                polyline: polyline,
                show_logo,
                show_photo,
            })
        })

    },
    parseJsonOrEmptyArray(jsonString) {
        try {
            const parsed = JSON.parse(jsonString);
            if (Array.isArray(parsed)) {
                // 检查数组元素的结构，并进行转换
                return parsed.map(item => {
                    if (typeof item === 'object' && 'url' in item) {
                        return item; // 已经是 { url: 'https://xxxxx' } 格式
                    } else if (typeof item === 'object' && item.url) {
                        return item.url; // 处理 { url: { url: 'https://xxxxx' } } 格式
                    } else {
                        return {}; // 无效的对象格式，返回空对象
                    }
                });
            } else {
                return [];
            }
        } catch (e) {
            return [];
        }
    },


    // 经纬度计算距离
    getDistance(lat1, lng1, lat2, lng2) {

        var radLat1 = lat1 * Math.PI / 180.0;
        var radLat2 = lat2 * Math.PI / 180.0;
        var a = radLat1 - radLat2;
        var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
            Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137; // EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        s = s.toFixed(2);
        return parseFloat(s);
    },

    on_travel(e) {
        let that = this
        let location = ''
        let location_id = e.currentTarget.dataset.location_id //定位类型 ,商铺定位 车辆定位 三轮定位

        let delivery_address_name = ''
        let address = ''
        if (this.data.wms_address) {
            if (this.data.wms_address.delivery_address_name.length > 0) {
                delivery_address_name = this.data.wms_address.delivery_address_name
            }

            if (this.data.wms_address.remark.length > 0) {
                address += ' *备注：' + this.data.wms_address.remark
            }
            if (location_id === "0") {
                location = this.data.wms_address.location
                delivery_address_name = '[门店]' + delivery_address_name
            } else if (location_id === "1") {
                location = this.data.wms_address.tricycle_stop_location
                delivery_address_name = '[三轮车驻车点]' + delivery_address_name
            } else if (location_id === "2") {
                location = this.data.wms_address.vehicle_stop_location
                delivery_address_name = '[货车驻车点]' + delivery_address_name
            }
        }

        if (location.indexOf(',')) {
            let location_parts = location.split(',')
            wx.openLocation({
                name: delivery_address_name,
                address: address,
                longitude: Number(location_parts[0]),
                latitude: Number(location_parts[1]),
            })
        }
    },
    /**
         * 默认打开折叠
         */
    onChange(event) {
        this.setData({
            activeNames: event.detail,
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {


    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    //这个函数是一开始点击事件触发的：
    async authorization() {
        let self = this
        try {
            await this.getWxLocation()//等待
        } catch (error) {
            Model({
                title: '温馨提示',
                tip: '获取权限失败，需要获取您的地理位置才能为您提供更好的服务！是否授权获取地理位置？',
                showCancel: true,
                confirmText: '前往设置',
                cancelText: '取消',
                sureCall() {
                    self.toSetting()
                },
                cancelCall() { }
            })
            return
        }
    },

    getWxLocation() {
        let that = this
        if (that.is_update_location) {
            that.setData({
                'is_update_location': false,
                'update_location_text': '获取定位',
            })
            return
        }
        wx.showLoading({
            title: '定位中...',
            mask: true,
        })
        return new Promise((resolve, reject) => {
            let _locationChangeFn = (res) => {
                wx.hideLoading()
                wx.offLocationChange(_locationChangeFn)
            }
            wx.startLocationUpdate({
                success: (res) => {
                    wx.onLocationChange(_locationChangeFn)
                    resolve()
                },
                fail: (err) => {
                    wx.hideLoading()
                    reject()
                }
            })
        })
    },
    toSetting() {
        let self = this
        wx.openSetting({
            success(res) {
                if (res.authSetting["scope.userLocation"]) {
                    // res.authSetting["scope.userLocation"]为trueb表示用户已同意获得定位信息，此时调用getlocation可以拿到信息
                    self.authorization()
                }
            }
        })
    },

})
